package com.woniuxy.activiti.service;

import com.woniuxy.activiti.utils.SpringContextUtil;
import com.woniuxy.entity.EnterpriseCredit;
import com.woniuxy.entity.FlowInfo;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 工作流程共享
 *
 * @author xilei
 * @create 2021-11-12 16:55
 */
@Slf4j
@Service
public class ActFlowCommService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private UserService userService;
    @Autowired
    private EnterpriseCreditService enterpriseCreditService;
    @Autowired
    private HistoryService historyService;

    /**
     * 流程部署定义
     *
     * @param flowInfo
     */
    public void saveNewDeploy(FlowInfo flowInfo) {

        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource(flowInfo.getFilepath())
                .name(flowInfo.getFlowname())
                .deploy();
        System.out.println("流程部署ID:" + deployment.getId());
        System.out.println("流程部署名称：" + deployment.getName());
    }

    /**
     * 启动流程实例
     *
     * @param formKey
     * @param beanName
     * @param bussinessKey
     * @param id
     * @return
     */
    @DependsOn("springContextUtils")
    public ProcessInstance startProcess(String formKey, String beanName, String bussinessKey, int id) {
        System.out.println("99999999999" + SpringContextUtil.getBean(beanName));
        System.out.println("getbean:" + SpringContextUtil.getBean("flowService"));
        IActFlowCustomService customService = (IActFlowCustomService) SpringContextUtil.getBean(beanName);
        log.info("<准备启动流程>----修改流程状态");
        customService.startRunTask(id);
        Map<String, Object> variables = customService.setvariables(id);
        variables.put("bussinessKey", bussinessKey);
        log.info("<启动流程>,formKey:{},bussinessKey:{}", formKey, bussinessKey);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(formKey, bussinessKey, variables);
        String processDefinitionId = processInstance.getProcessDefinitionId();
        log.info("<启动流程>-成功了，流程实例ID为：processDefinitionId:{}", processDefinitionId);
        return processInstance;
    }

    /**
     * 查看个人任务列表
     *
     * @param userid
     * @return
     */
    public List<Map<String, Object>> myTaskList(String userid) {
        TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(userid);
        System.out.println("taskquery:" + taskQuery);
        List<Task> list = taskQuery.orderByTaskCreateTime().desc().list();
        System.out.println("list:" + list);
        List<Map<String, Object>> listmap = new ArrayList<>();

        for (Task task : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("taskid", task.getId());
            map.put("taskname", task.getName());
            map.put("description", task.getDescription());
            map.put("priority", task.getPriority());
            map.put("owner", task.getOwner());
            map.put("assignee", task.getAssignee());
            map.put("delegationState", task.getDelegationState());
            map.put("processInstanceId", task.getProcessInstanceId());
            map.put("executionId", task.getExecutionId());
            map.put("processDefinitionId", task.getProcessDefinitionId());
            map.put("createTime", task.getCreateTime());
            map.put("taskDefinitionKey", task.getTaskDefinitionKey());
            map.put("dueDate", task.getDueDate());
            map.put("category", task.getCategory());
            map.put("parentTaskId", task.getParentTaskId());
            map.put("tenantId", task.getTenantId());
//            有问题
            System.out.println("assignee:" + task.getAssignee());
            User userinfo = userService.getUser(Integer.valueOf(task.getAssignee()));
            System.out.println("userInfo:" + userinfo);
            map.put("assigneeUser", userinfo.getUsername());
            listmap.add(map);
        }

        System.out.println("listmap: " + listmap);
        return listmap;
    }

    /**
     * 查看个人任务信息
     *
     * @param userid
     * @return
     */
    public List<Map<String, Object>> myTaskInfoList(String userid) {
        TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(userid);
        List<Task> list = taskQuery.orderByTaskCreateTime().desc().list();
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();

        System.out.println("-===++++++userId:" + userid);
        for (Task task : list) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("taskid", task.getId());
            map.put("assignee", task.getAssignee());
            map.put("processInstanceId", task.getProcessInstanceId());
            map.put("executionId", task.getExecutionId());
            map.put("processDefinitionId", task.getProcessDefinitionId());
            map.put("createTime", task.getCreateTime());
            ProcessInstance processInstance = (ProcessInstance) runtimeService.createExecutionQuery()
                    .processDefinitionId(task.getProcessInstanceId()).singleResult();
            System.out.println("什么东西" + task.getProcessInstanceId());
            System.out.println("什么东西" + processInstance);
            String id = task.getProcessDefinitionId().split(":")[1];
            EnterpriseCredit enterpriseCredit = enterpriseCreditService.findCreditById(Integer.valueOf(id));
            User user = userService.getUser(enterpriseCredit.getId());
                        map.put("flowUserName", user.getUsername());
                        map.put("flowType", "授信审批啊");
                        map.put("flowStartTime", enterpriseCredit.getTaskStartTime());
//            if (processInstance != null) {
//                System.out.println("不是空1");
//                String businessKey = processInstance.getBusinessKey();
//                if (!StringUtils.isBlank(businessKey)) {
//                    System.out.println("不是空2");
//                    String type = businessKey.split(":")[0];
//                    String id = businessKey.split(":")[1];
//                    if (type.equals("enterprisecredit")) {
//                        System.out.println("不是空3");
//                        EnterpriseCredit enterpriseCredit = enterpriseCreditService.findOne(Integer.valueOf(id));
//                        User user = userService.getUser(enterpriseCredit.getId());
//                        map.put("flowUserName", user.getUsername());
//                        map.put("flowType", "授信审批啊");
//                        map.put("flowStartTime", enterpriseCredit.getTask_start_time());
//                    }
//                }
//            }
            System.out.println("222" + map);
            listmap.add(map);
            System.out.println("333" + listmap);
        }
        return listmap;
    }

    /**
     * 完成提交任务
     *
     * @param remark
     * @param taskId
     * @param userId
     */
    public void completeProcess(String remark, String taskId, String userId) {
//        查询任务,根据任务id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            log.error("completeProcess流程---task is null!任务为空！");
            return;
        }
//        获取任务流程id，根据对象
        String processInstanceId = task.getProcessInstanceId();
//        设置审批人的id
        Authentication.setAuthenticatedUserId(userId);
//        添加记录
        taskService.addComment(taskId, processInstanceId, remark);
        System.out.println("------------------开始炒作玩成任务-----------------");
        System.out.println("任务id：" + taskId);
        System.out.println("负责人id：" + userId);
        System.out.println("流程实例id：" + processInstanceId);
//        完成办理
        taskService.complete(taskId);
        System.out.println("------------------结束炒作玩成任务-----------------");
    }

    /**
     * 查询历史记录
     *
     * @param businessKey
     */
    public void searchHistoty(String businessKey) {
        List<HistoricProcessInstance> list1 = historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceBusinessKey(businessKey).list();
        if (CollectionUtils.isEmpty(list1)) {
            return;
        }
        String processDefinitionId = list1.get(0).getProcessDefinitionId();
        List<HistoricActivityInstance> list = historyService
                .createHistoricActivityInstanceQuery()
                .processDefinitionId(processDefinitionId)
                .orderByHistoricActivityInstanceStartTime()
                .asc().list();
        LinkedHashMap<String, Map<String, String>> mapMap = new LinkedHashMap<>();
        for (HistoricActivityInstance hiact : list) {
            if (StringUtils.isBlank(hiact.getAssignee())) {
                continue;
            }
            System.out.println("活动id：" + hiact.getId());
            System.out.println("流程实例id：" + hiact.getProcessInstanceId());
//            获取受让人
            User user = userService.getUser(Integer.valueOf(hiact.getAssignee()));
            System.out.println("办理人id：" + hiact.getAssignee());
            System.out.println("办理人名字：" + user.getUsername());
            System.out.println("开始时间：" + hiact.getStartTime());
            System.out.println("结束时间：" + hiact.getEndTime());
            System.out.println("流程步骤" + hiact.getActivityName());
            System.out.println("---------------------------------------------------------------------------");
        }

    }
}

